package com.kaesun.ufit.treadmill;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.kaesun.ufit.hardware.CardioController;

public class MainActivity extends Activity implements View.OnClickListener, IOnHandlerMessage {

	public static final int TEXT_MAX_LINE = 2000;

	private static final int BUTTON_IDS[] = {
		R.id.buttonStart, R.id.buttonStop,
		R.id.buttonTimeSet,
		R.id.buttonAgeSet,
		R.id.buttonWeightSet,
		R.id.buttonSpeedSet,
		R.id.buttonInclineSet,
		R.id.buttonSpeedReq,
		R.id.buttonInclineReq,
		R.id.buttonHeartRateReq,
		R.id.buttonCalorieReq,
		R.id.buttonTimeReq,
		R.id.buttonDistanceReq,
		R.id.buttonGoalHeartRateSet,
		R.id.buttonAutoReq,
	};

	private MainApplication mApp = null;
	private WeakRefHandler mHandler = null;

	private ScrollView mScrollView = null;
	private TextView mTextView = null;
	private AlertDialog mAlertDialog = null;


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		for (int i=0; i<BUTTON_IDS.length; i++) {
			findViewById(BUTTON_IDS[i]).setOnClickListener(this);
		}

		mApp = (MainApplication)getApplication();
		mHandler = new WeakRefHandler((IOnHandlerMessage)this);

		mScrollView = (ScrollView) findViewById(R.id.ReadField);
		mTextView = (TextView) findViewById(R.id.ReadValues);

		log("Program Start !!!\n");
	}


	@Override
	protected void onDestroy() {

		super.onDestroy();
	}

	@Override
	protected void onPause() {
		//mHandler.removeMessages(HANDLER_TIMER);
		if (null != mAlertDialog) {
			if (mAlertDialog.isShowing()) {
				mAlertDialog.dismiss();
			}
			mAlertDialog = null;
		}

		super.onPause();
	} 

	@Override
	protected void onResume() {
		mApp.setHandler(mHandler, false);
		//mHandler.sendEmptyMessageDelayed(HANDLER_TIMER, INTERVAL_TIMER);

		super.onResume();
	}

	@Override
	public void onClick(View arg0) {
		String strRet = "";

		switch (arg0.getId()) {
		case R.id.buttonStart:
			log("CMD_START_STOP + R");
			strRet = mApp.cardioController(CardioController.CMD_START_STOP, 1);
			break;
		case R.id.buttonStop:
			log("CMD_START_STOP + E");
			strRet = mApp.cardioController(CardioController.CMD_START_STOP, 0);
			break;
		case R.id.buttonTimeSet:
		case R.id.buttonAgeSet:
		case R.id.buttonWeightSet:
		case R.id.buttonSpeedSet:
		case R.id.buttonInclineSet:
		case R.id.buttonGoalHeartRateSet:
			showInputDialog(arg0.getId());
			return;
		case R.id.buttonSpeedReq:
			log("CMD_REQ_SPEED");
			strRet = mApp.cardioController(CardioController.CMD_REQ_SPEED, 0);
			break;
		case R.id.buttonInclineReq:
			log("CMD_REQ_INCLINE");
			strRet = mApp.cardioController(CardioController.CMD_REQ_INCLINE, 0);
			break;
		case R.id.buttonHeartRateReq:
			log("CMD_REQ_HEARTRATE");
			strRet = mApp.cardioController(CardioController.CMD_REQ_HEARTRATE, 0);
			break;
		case R.id.buttonCalorieReq:
			log("CMD_REQ_CALORIE");
			strRet = mApp.cardioController(CardioController.CMD_REQ_CALORIE, 0);
			break;
		case R.id.buttonTimeReq:
			log("CMD_REQ_TIME");
			strRet = mApp.cardioController(CardioController.CMD_REQ_TIME, 0);
			break;
		case R.id.buttonDistanceReq:
			log("CMD_REQ_DISTANCE");
			strRet = mApp.cardioController(CardioController.CMD_REQ_DISTANCE, 0);
			break;
		case R.id.buttonAutoReq:
			log("CMD_REQ_AUTO");
			strRet = mApp.cardioController(CardioController.CMD_REQ_AUTO, 0);
			break;
		default:
			return;
		}
		log(strRet);
	}

	@Override
	public void handleMessage(Message msg) {
		if ((MainApplication.HANDLER_RX_CARDIOCONTROLLER == msg.what) && (0 < msg.arg1)) {
			int size = msg.arg1;
			byte[] bytes = (byte[])msg.obj;

			StringBuffer sb = new StringBuffer(size*3 + 1);
			for (int i=0; i<size; i++) {
				if (0x10 > ((int)bytes[i] & 0xFF)) {
					sb.append('0');
				}
				sb.append(Integer.toString(bytes[i] & 0xFF, 16));
				sb.append(' ');
			}
			log("RECV : " + sb.toString());
		}
	}


	private void showInputDialog(int step) {
		LinearLayout linear = (LinearLayout)View.inflate(this, R.layout.dialog_input, null);
		TextView textView = (TextView)linear.findViewById(R.id.text_title);
		final int fStep = step;
		final EditText fEditInput = (EditText)linear.findViewById(R.id.edit_input);

		switch (fStep) {
		case R.id.buttonTimeSet:
			textView.setText(" TimeSet : mmss");
			break;
		case R.id.buttonAgeSet:
			textView.setText(" AgeSet : xxx");
			break;
		case R.id.buttonWeightSet:
			textView.setText(" WeightSet : xxx");
			break;
		case R.id.buttonSpeedSet:
			textView.setText(" SpeedSet : xxx");
			break;
		case R.id.buttonInclineSet:
			textView.setText(" InclineSet : xxx");
			break;
		case R.id.buttonGoalHeartRateSet:
			textView.setText(" GoalHeartRateSet : xxx");
			break;
		default:
			return;
		}

		if (null != mAlertDialog) {
			if (mAlertDialog.isShowing()) {
				mAlertDialog.dismiss();
			}
			mAlertDialog = null;
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setView(linear)
		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String input = fEditInput.getText().toString();

				switch (fStep) {
				case R.id.buttonTimeSet:
					log("CMD_SET_TIME: " + mApp.cardioController(CardioController.CMD_SET_TIME, Integer.parseInt(input)));
					break;
				case R.id.buttonAgeSet:
					log("CMD_SET_AGE: " + mApp.cardioController(CardioController.CMD_SET_AGE, Integer.parseInt(input)));
					break;
				case R.id.buttonWeightSet:
					log("CMD_SET_WEIGHT: " + mApp.cardioController(CardioController.CMD_SET_WEIGHT, Integer.parseInt(input)));
					break;
				case R.id.buttonSpeedSet:
					log("CMD_SET_SPEED: " + mApp.cardioController(CardioController.CMD_SET_SPEED, Integer.parseInt(input)));
					break;
				case R.id.buttonInclineSet:
					log("CMD_SET_INCLINE: " + mApp.cardioController(CardioController.CMD_SET_INCLINE, Integer.parseInt(input)));
					break;
				case R.id.buttonGoalHeartRateSet:
					log("CMD_SET_GOALHEARTRATE: " + mApp.cardioController(CardioController.CMD_SET_GOALHEARTRATE, Integer.parseInt(input)));
					break;
				}
			}
		})
		.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		mAlertDialog = builder.create();
		mAlertDialog.show();
	}

	private void log(String str) {
		/*Log.e(TAG, str);
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();*/
		appendData(str);
		appendData("\n");
	}

	private void appendData(final String data) {
		mTextView.append(data);

		final int overLine = mTextView.getLineCount() - TEXT_MAX_LINE;
		if (overLine > 0) {
			int IndexEndOfLine = 0;
			final CharSequence charSequence = mTextView.getText();

			for (int i = 0; i < overLine; i++) {
				do {
					IndexEndOfLine++;
				} while (IndexEndOfLine < charSequence.length()
						&& charSequence.charAt(IndexEndOfLine) != '\n');
			}

			if (IndexEndOfLine < charSequence.length()) {
				mTextView.getEditableText().delete(0, IndexEndOfLine + 1);
			} else {
				mTextView.setText("");
			}
		}

		mScrollView.smoothScrollTo(0, mTextView.getHeight() + 30);
	}
}
